//获取应用实例
const app = getApp()
var util = require('../../utils/util.js');
Page({
  data: {
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    isHide: false,
    text:'',
    "bnrUrl": [{
      "url": "../../images/lunbo1.jpg"
    }, {
        "url": "../../images/lunbo2.jpg"
    }, {
        "url": "../../images/lunbo3.jpg"
    }],
    messageUrl: [{
      "url": "../../images/u95.jpeg"
    }, {
        "url": "../../images/u89.jpeg"
      }, {
        "url": "../../images/u94.jpeg"
      }],
    "tuangou": 1,
    "tuangouType": -1,
    "miaosha": 1,
    "miaoshaType": -1,
    'array': [{ src: "../../images/guide-1.png", text: "新手指南" },
      { src: "../../images/guide-2.png", text: "我的收藏" },
      { src: "../../images/guide-3.png", text: "常见问题" },
      { src: "../../images/guide-4.png", text: "系统消息" }],
    
      tuangou_icon:'../../images/group.png',
      tuangou_good_img:'http://zkpic.huiyunbao.cn/pic/cardImage/三轮秒杀图.jpg吕.jpg',
      tuangou_good_name:'保温杯',
      tuangou_good_price:'66',
      tuangou_good_count:"10",
      tuangou_title:"",
      tuangou_id : '',
      tuangou_pro_id : '',

      miaosha_icon: '../../images/spike.png',
      miaosha_good_img: 'http://zkpic.huiyunbao.cn/pic/cardImage/三轮秒杀图.jpg吕.jpg',
      miaosha_good_name:'活动已结束',
      miaosha_good_price: '99',
      miaosha_good_count: "28",
      miaosha_title:'',
      miaosha_id : '',
      miaosha_pro_id : '',

    xieyi: false,
    form_phone:'',
    form_name:'',
    form_code:'',
    btnTitle:'获取验证码',
    sendColor: '#f1a06e',
    smsFlag: false,
    snsMsgWait: 60,
    p_head:'',
    p_name:'test',
    p_phone:'13512457899',
    m_head:'',
    items:[
      { name: '是', value: 1 },
      { name: '否', value: 0, checked: 'true' },
    ],
    region: [],
    shop:0,
    status:0  //1.留言板 2.手机号注册 3.首页
  },
  onLoad: function (options){
    console.log("options:",options)
    var that = this;
    that.initRegion();
    
    // 查看是否授权
    wx.getSetting({
      success: function (res) {
        if (res.authSetting['scope.userInfo']) {
          wx.getUserInfo({
            success: function (res) {
              // 用户已经授权过,不需要显示授权页面,所以不需要改变 isHide 的值
              // 根据自己的需求有其他操作再补充
              // 我这里实现的是在用户授权成功后，调用微信的 wx.login 接口，从而获取code
              wx.login({
                success: res => {
                  // 获取到用户的 code 之后：res.code
                  console.log("用户的code:" + res.code);
                  // 可以传给后台，再经过解析获取用户的 openid
                  // 或者可以直接使用微信的提供的接口直接获取 openid ，方法如下：
                  // wx.request({
                  //     // 自行补上自己的 APPID 和 SECRET
                  //     url: 'https://api.weixin.qq.com/sns/jscode2session?appid=自己的APPID&secret=自己的SECRET&js_code=' + res.code + '&grant_type=authorization_code',
                  //     success: res => {
                  //         // 获取到用户的 openid
                  //         console.log("用户的openid:" + res.data.openid);
                  //     }
                  // });
                }
              });
            }
          });
        } else {
          // 用户没有授权
          // 改变 isHide 的值，显示授权页面
          that.setData({
            isHide: true
          });
        }
      }
    });
    that.homeReuqest()
  },

  homeReuqest:function(){
    var that = this
    //首页请求数据
    wx.getStorage({
      key: 'openid',
      success: function (res) {
        let openid = res.data
        wx.showLoading({
          title: '加载中',
        })
        wx.request({
          url: app.globalData.URL + '/app/home/home?openid=' + openid,
          success: function (res) {
            wx,wx.hideLoading()
            console.log(res.data)
            if (res.data.flag == 1) {
              console.log('新用户')
              that.setData({
                status: 1
              })
              wx.hideTabBar({})
            } else if (res.data.flag == 2) {
              console.log('合伙人')
              that.setData({
                status: 2,
                p_head: res.data.parterUser.headImgUrl,
                p_name: res.data.parterUser.nickName,
                p_phone: res.data.parterUser.telPhone,
                m_head: res.data.user.headImgUrl
              })
              wx.hideTabBar({})
              //拿到sessionid
              wx.request({
                url: app.globalData.URL + '/app/WeChatOAuth/getSessionId',
                success: function (res) {
                  console.log('session', res.data)
                  wx.setStorageSync('sessionId', 'jeeplus.session.id=' + res.data)
                }
              })
            } else {
              wx.showTabBar({})
              that.setData({
                status: 3,

                tuangou: res.data.tuangou,
                tuangouType: res.data.tuangouType,
                miaosha: res.data.miaosha,
                miaoshaType: res.data.miaoshaType,

                tuangou_good_img: res.data.bulk.picture,
                tuangou_good_name: res.data.bulk.productName,
                tuangou_good_price: res.data.bulk.price,
                tuangou_good_count: res.data.bulk.inventory,
                tuangou_id: res.data.bulk.id,
                tuangou_pro_id: res.data.bulk.product,
                tg_start: res.data.bulk.startTime,

                miaosha_good_img: res.data.seckill.picture,
                miaosha_good_name: res.data.seckill.productName,
                miaosha_good_price: res.data.seckill.price,
                miaosha_good_count: res.data.seckill.inventory,
                miaosha_id: res.data.seckill.id,
                miaosha_pro_id: res.data.seckill.product,
                ms_start: res.data.seckill.startTime
              })



              if (res.data.tuangouType == "1") {
                that.setData({
                  tuangou_title: '团购已经结束'
                })
              } else if (res.data.tuangouType == '-1') {
                if (res.data.tuangou == '1') {
                  that.setData({
                    tuangou_title: '团购已经开始'
                  })
                } else if (res.data.tuangou == '-1') {
                  that.setData({
                    tuangou_title: '团购倒计时' + that.data.tg_clock
                  })
                }
              }

              if (res.data.miaoshaType == "1") {
                that.setData({
                  miaosha_title: '秒杀已经结束'
                })
              } else if (res.data.miaoshaType == '-1') {
                if (res.data.miaosha == '1') {
                  that.setData({
                    miaosha_title: '秒杀已经开始'
                  })
                } else if (res.data.miaosha == '-1') {
                  that.ms_countdown(that)
                }
              }
            }

          }
        })
      },
    })
  },
  // 秒杀倒计时
  ms_countdown:function(that) {
     var EndTime = new Date(that.data.ms_start).getTime() || [];
     // console.log(EndTime);
     var NowTime = new Date().getTime();
     var total_micro_second = EndTime - NowTime || [];  //单位毫秒
     if(total_micro_second < 0) {
        // console.log('时间初始化小于0，活动已结束状态');
        total_micro_second = 1;   //单位毫秒 ------ WHY？
      return
     }
     that.setData({
      miaosha_title: '秒杀倒计时' + that.dateformat(total_micro_second)  //若已结束，此处输出'0天0小时0分钟0秒'
     });
     setTimeout(function () {
        total_micro_second -= 1000;
        that.ms_countdown(that);
     }, 1000)
  },
  // 团购倒计时
  tg_countdown: function (that) {
    var EndTime = new Date(that.data.tg_start).getTime() || [];
    // console.log(EndTime);
    var NowTime = new Date().getTime();
    var total_micro_second = EndTime - NowTime || [];  //单位毫秒
    if (total_micro_second < 0) {
      // console.log('时间初始化小于0，活动已结束状态');
      total_micro_second = 1;   //单位毫秒 ------ WHY？
      return
    }
    that.setData({
      tuangou_title: '团购倒计时' + that.dateformat(total_micro_second)  //若已结束，此处输出'0天0小时0分钟0秒'
    });
   
     setTimeout(function () {
        total_micro_second -= 1000;
        that.tg_countdown(that);
     }, 1000)
  },
  // 时间格式化输出，如11天03小时25分钟19秒 每1s都会调用一次
  dateformat:function(micro_second) {
     // 总秒数
     var second = Math.floor(micro_second / 1000);
     // 天数
     var day = Math.floor(second / 3600 / 24);
     // 小时
     var hr = Math.floor(second / 3600 % 24);
     // 分钟
     var min = Math.floor(second / 60 % 60);
     // 秒
     var sec = Math.floor(second % 60);
     return day + "天" + hr + "时" + min + "分" + sec + "秒";
  },

  nameInput:function(e){
    console.log(e.detail.value)
    this.setData({
      form_name:e.detail.value
    })
  },
  phoneInput: function (e) {
    console.log(e.detail.value)
    this.setData({
      form_phone: e.detail.value
    })
  },
  codeInput: function (e) {
    console.log(e.detail.value)
    this.setData({
      form_code: e.detail.value
    })
  },
  check:function(e){
    console.log("check",e)
    var xieyi = this.data.xieyi;
    this.setData({
      xieyi: !xieyi
    })
  },

  getCode:function(){
    if (this.data.form_phone.length !== 11) {
      wx.showToast({
        title: '请填写正确手机号',
        image: '../../images/error.png',
      })
      return;
    }
    if (!(/^1[3456789]\d{9}$/.test(this.data.form_phone))) {
      wx.showToast({
        title: '请填写正确手机号',
        image: '../../images/error.png',
      })
      return;
    }

    // 60秒后重新获取验证码
    var inter = setInterval(function () {
      this.setData({
        smsFlag: true,
        sendColor: '#cccccc',
        btnTitle: this.data.snsMsgWait + 's后重发',
        snsMsgWait: this.data.snsMsgWait - 1
      });
      if (this.data.snsMsgWait < 0) {
        clearInterval(inter)
        this.setData({
          sendColor: '#f1a06e',
          btnTitle: '获取验证码',
          snsMsgWait: 60,
          smsFlag: false
        });
      }
    }.bind(this), 1000);

    //获取验证码
    var sessionId = wx.getStorageSync('sessionId');
    var that = this
    wx.request({
      url: app.globalData.URL + '/app/home/sendSmsCode?phone=' + that.data.form_phone,
      header: {
        "Content-Type": "application/json;charset=utf-8",
        "Cookie": sessionId
      },
      success: function (res) {
        console.log(res.data)
        if(res.data.flag == true){
          wx.showToast({
            title: '获取成功',
          })
        }else{
          wx.showToast({
            title: '获取失败,稍后再试',
          })
        }
      }
    })

  },

  /**
  * 初始化省市区
  */
  initRegion() {
    this.setData({
      region: [this.data.provinceName, this.data.cityName, this.data.countyName]
    });
  },

  bindRegionChange: function (e) {
    this.setData({
      provinceName: e.detail.value[0],
      cityName: e.detail.value[1],
      countyName: e.detail.value[2]
    })
  },

  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)
    this.setData({
      shop: e.detail.value
    })
  },
  //合伙人提交
  commit2:function(){
    if(this.data.form_name == ''){
      util.showErrorToast('请填写姓名');
      
    } else if (this.data.form_phone.length !== 11 || !(/^1[3456789]\d{9}$/.test(this.data.form_phone))) {
      util.showErrorToast('填写正确手机号');
      
    } else if (this.data.form_code == '') {
      util.showErrorToast('请填写验证码');
      
    } else if (this.data.provinceName == null) {
      util.showErrorToast('请选择省市区');

    } else if (this.data.shop == null) {
      util.showErrorToast('请选择是否有早教店');

    } else if (this.data.xieyi == false) {
      util.showErrorToast('请勾选协议');

    } else{
      var sessionId = wx.getStorageSync('sessionId');
      var openid = wx.getStorageSync('openid')
      var that = this
      var address = that.data.provinceName + '-' + that.data.cityName + '-' + that.data.countyName
     
      wx.request({
        url: app.globalData.URL + '/app/home/valiSmsCode?celPhone='+that.data.form_phone+'&realName='+that.data.form_name+'&code='+that.data.form_code + '&openid=' + openid + '&address=' + address + '&shop=' + that.data.shop,
      
        header: {
          "Content-Type": "application/json;charset=utf-8",
          "Cookie": sessionId
        },
        success: function (res) {
          console.log(res.data)
          if(res.data.flag==true){
            wx.showToast({
              title: '提交成功',
              success:function(){
                //改变状态 显示首页内容
                that.setData({
                  status:3
                })
                that.homeReuqest()
              }
            })
          }else{
            util.showErrorToast('提交失败');
          }
        }
      })

    }
  },

  textInput: function (e) {
    this.setData({
      text: e.detail.value
    })
    console.log("textarea", this.data.text)
  },
  commit:function(){
    if(this.data.text == ''){
      util.showErrorToast('请输入内容');
    }else{
      var that = this
      wx.getStorage({
        key: 'openid',
        success: function (res) {
          let openid = res.data
          wx.request({
            url: app.globalData.URL + '/app/fx/message/addMessages?content=' + that.data.text + '&openid=' + openid,
            success: function (res) {
              console.log(res)
              if (res.data.flag == true) {
                wx.showModal({
                  title: '',
                  content: '留言成功，客服会尽快联系您！',
                })
              }
            }
          })
        },
      })
    }  
  },
  menuTap:function(e){
   console.log(e.currentTarget.id)
   if (e.currentTarget.id == 0){
     wx.navigateTo({
       url: '../guide/guide',
     })
   } else if (e.currentTarget.id == 1){
     wx.navigateTo({
       url: '../collect/collect',
     })
   } else if (e.currentTarget.id == 2) {
     wx.navigateTo({
       url: '../problem/problem',
     })
   }else{
     wx.navigateTo({
       url: '../message/message',
     })
   }
 },

 toProduct_tuangou:function(e){
   var that = this
   let id = that.data.tuangou_id;
   let pro_id = that.data.tuangou_pro_id;
   
   if(that.data.tuangouType == '1'){
     wx.showToast({
       title: '团购已结束',
       icon: '',
       image: '../../images/error.png',
     })
   }else{
     wx.navigateTo({
       url: '../tuangouPro/tuangouPro?id=' + id + '&pro_id=' + pro_id,
     })
   }
   
 },

  toProduct_miaosha: function () {
    console.log("miaosha")
    var that = this
    let id = that.data.miaosha_id;
    let pro_id = that.data.miaosha_pro_id;

    if(that.data.miaoshaType == '1'){
      wx.showToast({
        title: '秒杀已结束',
        icon: '',
        image: '../../images/error.png',
      })
    }else{
      wx.navigateTo({
        url: '../miashaPro/miaoshaPro?id=' + id + '&pro_id=' + pro_id,
      })
    }
   
  }
  
})
